package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 通过网关对请求进行过滤,来进行鉴权以及用户的权限问题
 */
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER+1;
    }

    @Autowired
    private FilterProperties properties;

    @Override
    public boolean shouldFilter() {
        //1 获取请求对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI();
        List<String> allowPaths = properties.getAllowPaths();
        //配置文件中写白名单,对这些名单路径不进行(登录)过滤
        for (String allowPath : allowPaths) {
            if (uri.startsWith(allowPath)) {
                return false;
            }
        }
        return true;
    }

    @Autowired
    private JwtProperties prop;

    @Override
    public Object run() throws ZuulException {
        //1 获取请求对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            //获取cookie信息
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            //解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            // TODO 当前用户权限查询
            UserInfo userInfo = payload.getUserInfo();
            String role = userInfo.getRole();
            // TODO 基于角色查询该用户具有的访问权限

            String uri = request.getRequestURI();
            String method = request.getMethod();

        } catch (Exception e) {
            e.printStackTrace();
            //解析token失败
            log.error("【网关】解析token信息失败",e);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
        }
        return null;
    }
}
